"""
    客户端
    注册　登录　查询（单词注释，查询记录）　登出
    １．打开客户端，连接服务器　打印主页面根据用户输入，发送相应请求格式


    接收用户输入，
"""
from socket import *
import time
import re
import sys

class DictClit_Model():
    """
        建立连接
        创建页面视图
    """

    def __init__(self):
        self.sock = self.set_serv()

    def set_serv(self):
        sock = socket()
        sock.connect(('0.0.0.0', 1943))
        return sock

    def index_one(self):
        print("========欢迎来到万能英文查询系统========")
        print("===　　　　输入1进行新用户注册　　　　===")
        print("===　　　　输入2进行老用户登录　　　　===")
        print("===　　　　输入3退出英文查询系统　　　　===")
        print("====================================")

    def index_two(self):
        print("======　欢迎使用查询系统，亲爱的会员！======")
        print("===　　　　　输入1进行单词查询　　　　　 ===")
        print("===　　　　　输入2打印查询记录　　　　　 ===")
        print("===　　　　　输入3启动注销程序　　　　　 ===")
        print("======================================")

    def jump(self):
        time.sleep(0.1)
        print('正在为您跳转中..........')
        time.sleep(0.2)

    def byebye(self):
        print('注销中......')
        time.sleep(0.3)
        print('注销完毕，感谢您的使用，期待您的下次使用，再见！')


class DictClit_View():
    def __init__(self):
        self.model = DictClit_Model()
        self.collector = DictClit_Collector(self.model)

    def index_one(self):
        while True:
            self.model.index_one()
            data = input('请输入：')
            self.model.jump()
            if data == '1':
                self.creat()
            if data == '2':
                self.login()
            if data == '3':
                self.exit()



    def login(self):
        """登录"""
        username = input('请输入用户名:')
        password = input('请输入密码:')
        message = f'IN {username}-{password}'.encode()
        self.model.sock.send(message)  # 格式化请求 然后发送
        response = self.model.sock.recv(1024).decode()  # 判断客户端是否可以进行登录操作
        if response == '200':
            end = self.model.sock.recv(1024).decode()
            if end == '200':  # 判断服务器登录结果,登录成功跳转到二级界面
                print('登录成功')
                self.collector.index_two(username)
            else:
                print('账号密码错误,请重新输入')
        else:
            print('发送登录请求失败,请稍后重试')

    def creat(self):
        """注册"""
        username = input('请输入用户名:')
        password = input('请输入密码:')
        message = f'CREAT {username}-{password}'.encode()
        self.model.sock.send(message)  # 格式化请求 然后发送
        response = self.model.sock.recv(1024).decode()  # 判断客户端是否可以进行注册操作
        if response == '200':
            end = self.model.sock.recv(1024).decode()
            if end == '200':  # 判断服务器登录结果,登录成功跳转到二级界面
                print('注册成功')
                self.collector.index_two(username)
            else:
                print('注册失败,账号已存在,请重新输入')
        else:
            print('发送注册请求失败,请稍后重试')

    def exit(self):
        message = 'OUT out'.encode()
        self.model.sock.send(message)
        self.model.byebye()
        self.model.sock.close()
        sys.exit()


class DictClit_Collector():

    def __init__(self, sock):
        self.model = sock
        self.sock = self.model.sock

    def index_two(self, username):
        """二级界面"""
        while True:
            time.sleep(0.2)
            self.model.jump()
            self.model.index_two()
            data = input('请输入：')
            self.model.jump()
            if data == '1' or data == '2':
                self.query(data, username)
            elif data == '3':
                self.log_out()


    def log_out(self):
        self.model.byebye()
        self.sock.send(b'OUT out')
        self.sock.close()
        sys.exit()


    def query(self, data, username):
        "查询"
        if data == '1':
            word = input('请输入要查询的单词:')
            message = f'GET {word}'.encode()
            self.sock.send(message)
            time.sleep(0.2)
            self.sock.send(username.encode())
            response = self.sock.recv(1024)
            if response == b'200':
                mean = self.sock.recv(1024).decode()
                print(mean)
            else:
                print('单词不存在,请重新输入')
        else:
            message = 'GET SELECT'
            self.sock.send(message.encode())
            time.sleep(0.2)
            self.sock.send(username.encode())
            print('等待服务器验证')
            response = self.sock.recv(1024)
            print('验证完成开始接收服务器消息')
            if response == b'200':
                count = 0
                while True:
                    select = self.sock.recv(1024).decode()
                    if select == '##':
                        break
                    select_time_list = re.findall(r'(\d+)', select)
                    select_time = ''
                    for i in select_time_list:
                        select_time = select_time + i + ' '
                    word = re.findall(r'\w+',select)[1]
                    print(f'姓名:{username},查询单词:{word},查询时间:{select_time}')
                    count += 1
                print(f'查询完毕,已为您返回{count}条信息')
            else:
                print('暂无查询记录')


if __name__ == '__main__':
    test = DictClit_View()
    test.index_one()
